<template>
  <el-container style="height: 100%; min-width: 600px">
    <el-header>
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.input" placeholder="请输入用户名或id"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 功能栏 -->
      <el-row>
        <el-button type="success" icon="el-icon-plus" @click="addUserFormVisible = true" circle></el-button>
        <el-button type="primary" icon="el-icon-edit" @click="editDialogVisible = true" circle></el-button>
        <el-button type="danger" icon="el-icon-delete" @click="deleteAll" circle></el-button>
      </el-row>
    </el-header>

    <!-- 弹出框添加用户 -->
    <el-dialog title="添加用户" width="25%" center :visible.sync="addUserFormVisible">
      <el-form label-position="left" :model="form">
        <el-form-item label="用户ID" :label-width="formLabelWidth">
          <el-input v-model="form.user_id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.user_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.user_pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="form.user_age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.user_sex" size="medium">
            <el-radio border label="男"></el-radio>
            <el-radio border label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金币" :label-width="formLabelWidth">
          <el-input v-model="form.user_gold" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="积分" :label-width="formLabelWidth">
          <el-input v-model="form.user_score" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 弹出框编辑用户 -->
    <el-dialog width="25%" title="编辑用户" :visible.sync="editDialogVisible" center>
      <el-form label-position="left" :model="form">
        <el-form-item label="用户id" :label-width="formLabelWidth">
          <el-input :disabled="true" v-model="form.user_id" autocomplete="true"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth">
          <el-input v-model="form.user_pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.user_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户年龄" :label-width="formLabelWidth">
          <el-input v-model="form.user_age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" :label-width="formLabelWidth">
          <el-input v-model="form.user_sex" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户金币" :label-width="formLabelWidth">
          <el-input :disabled="true" v-model="form.user_gold" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户积分" :label-width="formLabelWidth">
          <el-input :disabled="true" v-model="form.user_score" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 用户头像弹框 -->
    <el-dialog title="修改用户图片" :visible.sync="userImgDialog" width="20%">
      <el-upload class="upload-demo" name="file" drag :action="uploadAction"
        :on-success="handleAvatarSuccess.bind(this, index)">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userImgDialog = false">取 消</el-button>
        <el-button type="primary" @click="userImgDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-main>
      <!-- 表格 -->
      <el-table v-loading="tableLoading" type="index" align="center" :data="tableData" style="width: 100%" height="100%"
        id="table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="user_id" fixed label="用户ID" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_name" label="用户名" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_pass" label="密码" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_age" label="年龄" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_sex" label="性别" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_gold" label="金币" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_score" label="积分" width="" align="center">
        </el-table-column>
        <el-table-column prop="user_img" label="头像" width="" align="center">
          <template slot-scope="scope">
           <el-avatar shape="square" :size="50" :src="scope.row.user_img" @click="userImgTap(scope,'head')"></el-avatar>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="user_bg" label="背景图" width="" align="center">
          <template slot-scope="scope">
            <el-image class="user_bg" fit="cover" :src="scope.row.user_bg" alt="">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-switch @change="switchChange(scope.$index, scope.row)" v-model="tableData[scope.$index].user_permission"
              active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除此用户吗？" @confirm="handleDelete(scope.$index, scope.row)">
              <el-button slot="reference" size="mini" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script>
import { HttpGet, HttpPost } from "@/api/http";

export default {
  name: "User",
  data() {
    return {
      index: "",
      // 搜索框
      formInline: {
        input: "",
      },
      // 弹出框添加用户
      addUserFormVisible: false,
      //用户图片弹框
      userImgDialog: false,
      form: {
        user_id: "",
        user_name: "",
        user_pass: "",
        user_age: "",
        user_sex: "",
        user_gold: "",
        user_score: "",
        user_img: "",
        user_bg: "",
        user_permission: "",
      },
      uploadAction: "",
      formLabelWidth: "120px",
      //弹出框编辑用户
      editDialogVisible: false,
      // 用户表格
      tableData: [],
      //加载中
      tableLoading: true,
      //复选框数组
      multipleSelection: [],
    };
  },

  created() {
    this.getTable();
  },
  methods: {
    divclick(scope) {
      console.log(scope);
    },
    // 搜索框
    onSubmit() {
      let keyword = this.formInline.input;
      this.tableData.forEach((item) => {
        //清除所有高亮
        item.rowlight = "";
        if (item.user_name == keyword || item.user_id == keyword) {
          //标记该行高亮
          item.rowlight = 1;
        }
      });
    },
    //权限开关事件+
    async switchChange(index, row) {
      let user_permission = row.user_permission ? "1" : "0";
      let user_id = row.user_id;
      try {
        let res = await HttpGet({
          url: "/user/changePms",
          params: { user_id, user_permission },
        });
        if (res.data.code == 200) {
          this.$message.success("修改用户权限成功");
        } else {
          this.$message.error("修改用户权限失败");
        }
      } catch (err) {
        this.$message.error(err);
      }
    },
    //复选框改变函数
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //批量删除
    deleteAll() {
      let that = this;
      if (this.multipleSelection.length < 1) {
        this.$message.warning("请选择删除的用户");
        return;
      }
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let checkUsers = this.multipleSelection;
          let usersId = [];
          checkUsers.forEach((item) => {
            usersId.push(item.user_id);
          });
          try {
            let res = await HttpPost({
              url: "/user/deleteUsers",
              data: usersId.toString(),
            });
            if (res.data.code == 200) {
              that.getTable();
              this.$message.success("删除成功!");
            }
          } catch (e) {
            console.log(e);
            this.$message.error("出错了，删除用户失败");
          }
        })
        .catch(() => {
          this.$message.warning("已取消删除");
        });
    },
    // 添加用户
    async addSubmit() {
      this.addUserFormVisible = false;
      try {
        let res = await HttpPost({ url: "/user/add", data: this.form });
        if (res.data.code == 200) {
          this.getTable();
          this.$message.success("添加用户成功");
          for (let item in this.form) {
            this.form[item] = "";
          }
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    // 点击单个编辑
    handleEdit(index, row) {
      // console.log(index, row);
      this.editDialogVisible = true;
      this.form.user_id = row.user_id;
      this.form.user_pass = row.user_pass;
      this.form.user_name = row.user_name;
      this.form.user_age = row.user_age;
      this.form.user_sex = row.user_sex;
      this.form.user_gold = row.user_gold;
      this.form.user_score = row.user_score;
      this.index = index;
    },
    //点击上传用户头像
    userImgTap(params) {
      let userId = params.row.user_id;
      let imageType = params.column.label == "头像" ? "head" : "bg";
      this.uploadAction = `http://121.37.209.61:8888/user/uploadImg?userId=${userId}&imgType=${imageType}`;
      this.userImgDialog = true;
    },
    // 头像上传成功钩子
    handleAvatarSuccess(index, res, file, fileList) {
      console.log(res);
      if (res.code == 200) {
        this.getTable();
        this.$message.success("上传头像成功");
        return;
      }
      this.$message.error("上传头像失败");
    },
    //编辑完成提交事件
    async editSubmit() {
      try {
        let res = await HttpPost({
          url: "/user/update",
          data: this.form,
        });
        if (res.data.code == 200) {
          this.$message({
            message: "成功,修改用户信息成功！",
            type: "success",
          });
          this.tableData[this.index] = this.form
          this.editDialogVisible = false;
        } else {
          that.$message.error("错误，修改用户信息失败！");
        }
      } catch (e) {
        that.$message.error("服务器错误，修改用户信息失败！", e);
      }
    },
    async handleDelete(index, row) {
      try {
        let res = await HttpGet({
          url: "/user/delete",
          params: { user_id: row.user_id },
        });
        if (res.data.code == 200) {
          this.$message.success("删除成功");
          //假删除
          this.tableData.splice(index, 1);
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    //请求表格数据，刷新列表
    async getTable() {
      this.tableLoading = true;
      let res = await HttpGet({ url: "/user/all" });
      if (res.data.code == 200) {
        res.data.data.forEach((item) => {
          item.user_permission = item.user_permission == 1 ? true : false;
        });
        this.tableData = res.data.data;
        this.tableLoading = false;
      }
    },
  },
  computed: {},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-header {
  padding-top: 20px;
  display: flex;
  justify-content: space-between;
}

.el-main {
  min-width: 600px;
  height: 100%;
  overflow: hidden;
}

/* 添加用户上传头像 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

>>>.el-upload {
  width: 100%;
}

>>>.el-upload-dragger {
  width: 100%;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-header .el-input {
  width: 200px;
}

/* 用户列表图片 */
>>>.el-image__inner {
  height: 70px;
}

</style>
